﻿using System;
using System.Collections.Generic;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;
using Omu.ValueInjecter;

namespace Omu.AwesomeDemo.Infra.Builder
{
    public class IntsToEntities : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            return c.SourceProp.Name == c.TargetProp.Name
                   && c.SourceProp.Type.IsGenericType
                   && c.SourceProp.Type.GetGenericTypeDefinition() == typeof (IEnumerable<>)
                   && c.TargetProp.Type.IsGenericType
                   && c.TargetProp.Type.GetGenericTypeDefinition() == typeof (IEnumerable<>)
                   && c.SourceProp.Type.GetGenericArguments()[0] == typeof (int)
                   && c.TargetProp.Type.GetGenericArguments()[0].IsSubclassOf(typeof (Entity));
        }

        protected override object SetValue(ConventionInfo c)
        {
            if (c.SourceProp.Value == null) return null;
            var T = c.TargetProp.Type.GetGenericArguments()[0];
            dynamic repo = IoC.Resolve(typeof(IRepo<>).MakeGenericType(T));
            dynamic list = Activator.CreateInstance(typeof(List<>).MakeGenericType(T));

            foreach (var i in (c.SourceProp.Value as IEnumerable<int>))
                list.Add(repo.Get(i));
            return list;
        }
    }
}